package com.dhq.myapp.ui.identity

import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.dhq.myapp.Constant
import com.dhq.myapp.R
import com.dhq.myapp.base.BaseActivity
import com.dhq.myapp.base.adapter.RvBaseHolder
import com.dhq.myapp.base.adapter.RvManyLayoutAdapter
import com.dhq.myapp.bean.GroupsEntity
import com.dhq.myapp.bean.UploadImgEntity
import com.dhq.myapp.util.FileUtil
import com.dhq.myapp.util.GlassOptionUtil
import com.dhq.myapp.util.GlassUtil
import com.dhq.myapp.util.GlassUtil.FileChangeListener
import com.dhq.myapp.util.GlideImageLoadUtils
import com.dhq.myapp.util.IdentifyUtil
import com.dhq.myapp.util.MD5Utils
import com.dhq.myapp.util.WifiUtil
import com.dhq.myapp.util.ask.AsrListener
import com.dhq.myapp.util.ask.AsrMain
import com.dhq.myapp.util.dialog.DialogConvert
import com.dhq.myapp.util.dialog.DialogUtils
import com.dhq.myapp.util.dialog.ViewHolder
import com.dhq.myapp.util.http.BaseObserver
import com.dhq.myapp.widget.rcview.RCImageView
import com.lxj.xpopup.core.BasePopupView
import com.rokid.cxr.client.extend.CxrApi
import com.rokid.cxr.client.extend.controllers.FileController
import com.rokid.cxr.client.extend.infos.SceneStatusInfo
import com.rokid.cxr.client.extend.listeners.AudioStreamListener
import com.rokid.cxr.client.extend.listeners.SceneStatusUpdateListener
import com.rokid.cxr.client.extend.sync.FileListResponse
import com.rokid.cxr.client.extend.sync.RetrofitClient
import com.rokid.cxr.client.utils.ValueUtil
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * DESC
 * Created by douhaoqiang on 2025/10/17.
 */
class IdentityActivity : BaseActivity(), View.OnClickListener {

    private var currentTime: Long = 0

    private var tv_take_photo_status: TextView? = null;

    private var tv_asr_result: TextView? = null;

    private var iv_photo_img: ImageView? = null;
    private var iv_indetity_result: ImageView? = null;
    private var tv_indetity_result: TextView? = null;
    private var tv_token_photo: TextView? = null;
    private var tv_biology_select: TextView? = null;
    private lateinit var mWifiUtil: WifiUtil
    private lateinit var mGlassOptionUtil: GlassOptionUtil
    private lateinit var mGlassUtil: GlassUtil

    private var groupList = ArrayList<GroupsEntity>();
    private var mBiologyGroup: GroupsEntity? = null

    private val mainHandler = Handler(Looper.getMainLooper())
    private lateinit var updateTask: Runnable

    private lateinit var voiceCollector: RokidVoiceCollector;

    private var voiceFilePath = ""


    private lateinit var asrMain: AsrMain;


    override fun getLayoutId(): Int {
        return R.layout.activity_identify_lay
    }

    override fun initView() {
        getHeaderUtil().setHeaderTitle("拍照识别")
        tv_take_photo_status = findViewById<TextView>(R.id.tv_take_photo_status)
        tv_asr_result = findViewById<TextView>(R.id.tv_asr_result)
        tv_token_photo = findViewById<TextView>(R.id.tv_token_photo)
        iv_photo_img = findViewById<ImageView>(R.id.iv_photo_img)
        iv_indetity_result = findViewById<ImageView>(R.id.iv_indetity_result)
        tv_indetity_result = findViewById<TextView>(R.id.tv_indetity_result)
        tv_biology_select = findViewById<TextView>(R.id.tv_biology_select)

    }

    override fun initData() {
        tv_token_photo?.setOnClickListener(this)
        tv_biology_select?.setOnClickListener(this)
        mWifiUtil = WifiUtil();
        mGlassOptionUtil = GlassOptionUtil(this)
        mGlassUtil = GlassUtil(this)
        connectWifi(false);


        CxrApi.getInstance().setSceneStatusUpdateListener(object : SceneStatusUpdateListener {
            override fun onSceneStatusUpdated(p0: SceneStatusInfo?) {
                Log.e("onSceneStatusUpdated", p0.toString())

                runOnUiThread {
                    if (p0?.isAiAssistRunning == true) {
                        //ai开启对话模式
                        val success = voiceCollector.startCollect()
                        if (success) {

                            voiceFilePath = FileUtil.getVoiceFilePath(this@IdentityActivity);
                            voiceCollector.setVoiceFilePath(voiceFilePath);
                            tv_asr_result?.setText("开启语音识别模式")
                        }else{
                            voiceFilePath = "";
                            tv_asr_result?.setText("开启语音识别模式失败")
                        }
                    } else {
                        //对话模式关闭
                        voiceCollector.stopCollect()
                        tv_asr_result?.setText("关闭语音识别模式")
                        if(!TextUtils.isEmpty(voiceFilePath)){
                            goIndentifyVoice()
//                        var voiceData = FileUtil.getVoiceFileData(voiceFilePath)
//                        Log.e("语音数据",voiceData)
                        }
                    }
                }

            }
        })


//        addMediaListener();

        currentTime = System.currentTimeMillis();


//        showBiologyGroupDialog()


        // 定义要执行的任务
        updateTask = object : Runnable {
            override fun run() {
                // 更新UI
                CxrApi.getInstance().closeCustomView()

            }
        }

        initVoiceCollector();


        asrMain = AsrMain(this);



    }

    fun goIndentifyVoice(){

        if(TextUtils.isEmpty(voiceFilePath)){
            return
        }
//        var filePath = FileUtil.getVoicePath(this);
        asrMain.run(voiceFilePath,object : AsrListener{
            override fun success(dateStr: String) {
                Log.e("识别",dateStr)

                if (TextUtils.isEmpty(dateStr)){
                    tv_asr_result?.setText("语音识别数据是空")
                    return
                }

                if(dateStr.contains("拍照")||dateStr.contains("拍")||dateStr.contains("识别")){
                    tv_asr_result?.setText("语音识别-"+dateStr+"--语音指令--拍照")
                    tokenPhoto();
                }else{
                    tv_asr_result?.setText("语音识别-"+dateStr)
                }

            }

            override fun fail(dateStr: String) {
                tv_asr_result?.setText("语音识别失败-"+dateStr)
            }
        })
    }

    fun initVoiceCollector() {
        // 初始化语音采集器
        voiceCollector = RokidVoiceCollector(
            context = this,
            onAsrResult = { text ->
                // 语音识别结果回调
                Log.d("语音采集器", "识别结果: $text")
                runOnUiThread {
                    handleVoiceCommand(text)
                }
            },
            onError = { errorMsg ->
                // 错误处理
                Log.e("语音采集器", "语音采集错误: $errorMsg")
                runOnUiThread {
                    toast(errorMsg);
                }
            }
        )
    }

    private fun handleVoiceCommand(command: String) {
        when {
            command.contains("打开提词器") -> {
                // 执行相应操作
//                openTeleprompter()
            }

            command.contains("显示欢迎文本") -> {
//                showWelcomeText()
            }
            // 其他命令处理...
        }
    }


//    private val collector = RokidVoiceCollector(this,(asrText:String)=>{
//
//    },(asrText:String)=>{
//
//    })

//    // 第三方ASR客户端（需自行集成，此处以示例形式存在）
//    private val asrClient = ThirdPartyAsrClient(
//        onResult = { asrText -> onAsrResult?.invoke(asrText) },
//        onError = { errorMsg ->; onError?.invoke(errorMsg) }
//    )

    /**
     * 添加语音识别监听
     */
    fun openAudioIndentity() {


        var result = openAudioRecord(1, "AI_assistant")

        CxrApi.getInstance().setAudioStreamListener(object : AudioStreamListener {
            override fun onStartAudioStream(p0: Int, p1: String?) {

                Log.e("录音", "录音开始");
            }

            override fun onAudioStream(data: ByteArray?, offset: Int, length: Int) {
                Log.e("录音", "录音数据");
                if (data == null || data.size <= 0) {
                    Log.w("录音", "接收空音频数据，忽略")
                    return
                }
                Log.d("录音", "接收音频数据：长度=$(" + data.size + ") 字节")
                // 将音频数据传给ASR客户端（需截取有效数据：从offset开始，长度为length）
                val validData = data.copyOfRange(offset, offset + length)
                var voiceStr = convertAudioByteArrayToBase64(validData)
                Log.e("识别语音", voiceStr)
//                asrClient.sendAudioData(validData)
            }
        })

    }

    /**
     * 将ByteArray数组数据转换成字符串数据
     */
    fun convertAudioByteArrayToBase64(audioData: ByteArray): String {
        return Base64.encodeToString(audioData, Base64.NO_WRAP)
    }


    /**
     * 开启录音.
     *
     * @param codecType The stream codec type: 1:pcm, 2:opus.
     * @param streamType The stream type such as "AI_assistant", it is same as the stream type in audio stream listener.
     *
     * @return The status of open audio record.
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun openAudioRecord(codecType: Int, streamType: String?): ValueUtil.CxrStatus? {
        return CxrApi.getInstance().openAudioRecord(codecType, streamType)
    }

    /**
     * 关闭录音.
     *
     * @param streamType The stream type such as "AI_assistant", it is same as the stream type in audio stream listener.
     *
     * @return The status of close audio record.
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun closeAudioRecord(streamType: String): ValueUtil.CxrStatus? {
        return CxrApi.getInstance().closeAudioRecord(streamType)
    }


    override fun onPause() {
        super.onPause()
        closeAudioRecord("AI_assistant")
    }

    /**
     * 获取为同步的文件列表
     */
    fun getUnSyncFileList() {

        var address = CxrApi.getInstance().b;


        var mediaArr = FileController.generateMediaPaths(arrayOf(ValueUtil.CxrMediaType.PICTURE))
        RetrofitClient.getInstance().setBaseUrl("http://" + address + ":8848")
        var ss = RetrofitClient.createPartFromString(mediaArr[0])
        var result = RetrofitClient.getInstance().getService().getFileList(ss);

//        result.enqueue(FileCallback(FileController.getInstance(),object : FileListener{
//            override fun onResponse(filePath: String) {
//                getNeedIndentityImg(filePath)
//            }
//
//            override fun onFailure() {
//                TODO("Not yet implemented")
//            }
//        }))

        result.enqueue(object : Callback<FileListResponse?> {
            override fun onResponse(
                call: Call<FileListResponse?>,
                fileListResp: Response<FileListResponse?>
            ) {
                if (fileListResp.isSuccessful()) {
                    var fileList = fileListResp.body()?.data;
                    if (fileList!!.size > 0) {
                        getNeedIndentityImg(fileList[fileList!!.size - 1].absoluteFilePath)
                    }
                }

            }

            override fun onFailure(
                call: Call<FileListResponse?>,
                t: Throwable
            ) {

            }
        })


    }


    override fun onClick(view: View?) {
        when (view?.id) {

            R.id.tv_token_photo -> {
                sendTtsFeedback("发送消息")
                return
                //拍照
                if (mBiologyGroup == null) {
                    toast("请先选择类群")
                }

                if (mWifiUtil.getWiFiConnectionStatus() == true) {
                    //直接拍照
                    tokenPhoto();
                } else {
                    toast("请先连接wifi！")
//                    connectWifi(true);
                }

            }

            R.id.tv_biology_select -> {
                //跳转连接说明
                showBiologyGroupDialog()
            }

        }
    }

    fun addMediaListener() {

        mGlassUtil.setMediaFilesUpdateListener(object : FileChangeListener {
            override fun onFileChanged() {
                getUnSyncFileList();
//                getUnSyncFile()
//                mGlassUtil.getAllImageFile()
            }
        })

    }


    fun connectWifi(isTokenPhoto: Boolean) {
        mWifiUtil.connect(object : WifiUtil.WifiListener {
            override fun onConnected() {
                runOnUiThread {
                    addMediaListener()
                    toast("连接wifi成功，可以传递数据了！")


//                    CxrApi.getInstance().getUnsyncNum(unSyncCallback)
//                    if (isTokenPhoto) {
//                        tokenPhoto()
//                    }else{
//                        CxrApi.getInstance().getUnsyncNum(unSyncCallback)
//                    }
                }

            }

            override fun onDisconnected() {
                toast("wifi断开！")
            }

            override fun onFailed() {
                toast("连接wifi失败，重试中！")
                connectWifi(false)
            }
        })
    }

    fun getNeedIndentityImg(path: String) {
        mGlassUtil.getFile(path, object : GlassUtil.SyncListener {
            override fun onTakePhotoStart() {

            }

            override fun onTakePhotoSuccess(filePath: String) {

                showIndentityStatus("拍照完成" + filePath)
            }

            override fun onTakePhotoFailed() {

            }

            override fun onSyncStart() {

            }

            override fun onSingleFileSynced(fileName: String) {

                showIndentityStatus("拍照完成")
                showTakePhotoImg(fileName)
            }

            override fun onSyncFailed() {

            }

            override fun onSyncFinished() {

            }
        })
    }

    fun tokenPhoto() {


        mGlassUtil.takePhoto(object : GlassUtil.SyncListener {
            override fun onTakePhotoStart() {
                Log.e("拍照识别", "拍照开始")
                showIndentityStatus("拍照开始")
            }

            override fun onTakePhotoSuccess(filePath: String) {
                Log.e("拍照识别", "拍照完成" + filePath)
                showIndentityStatus("拍照完成" + filePath)
//                showTakePhotoImg(filePath)

            }

            override fun onTakePhotoFailed() {
                Log.e("拍照识别", "拍照失败")
                showIndentityStatus("拍照失败")
            }

            override fun onSyncStart() {
                Log.e("拍照识别同步", "同步开始")
                showIndentityStatus("同步开始")
            }

            override fun onSingleFileSynced(fileName: String) {
                Log.e("拍照识别同步", "同步完成")
                showIndentityStatus("拍照完成")
                showTakePhotoImg(fileName)
            }

            override fun onSyncFailed() {
                Log.e("拍照识别同步", "同步失败")
                showIndentityStatus("同步失败")
            }

            override fun onSyncFinished() {
                Log.e("拍照识别同步", "同步结束")
                showIndentityStatus("同步结束")

            }
        })

    }

    fun showIndentityStatus(status: String) {
        runOnUiThread {
            tv_take_photo_status?.setText(status)
        }

    }

    fun showTakePhotoImg(filePath: String) {
        runOnUiThread {
            Glide.with(this).load(filePath).into(iv_photo_img!!)

            notifyResult("绿萝", "")

        }
    }

    fun showIndentityResult(identifyName: String, filePath: String) {
        runOnUiThread {
            tv_indetity_result?.setText(identifyName)
//            Glide.with(this).load(filePath).into(iv_indetity_result!!)
            Glide.with(this).load(R.mipmap.ic_result_lvluo).into(iv_indetity_result!!)
        }
    }

    //通知显示识别结果
    fun notifyResult(identifyName: String, identifyImage: String) {
        showIndentityResult(identifyName, identifyImage)
        val text = "你的识别结果是绿萝"

//        CxrApi.getInstance().notifyAiStart();
////        val text = "这是唐代三彩马，高约60厘米，出土于洛阳..."
//        CxrApi.getInstance().sendStream(
//            ValueUtil.CxrStreamType.WORD_TIPS,
//            text.toByteArray(),
//            "guide_${System.currentTimeMillis()}.txt",
//            object : SendStatusCallback {
//                override fun onSendSucceed() { /* 成功 */ }
//                override fun onSendFailed(errorCode: ValueUtil.CxrSendErrorCode?) { /* 失败 */ }
//            }
//        )

        // 发送TTS内容到眼镜


//        sendTtsFeedback(text)

        var stauts = IdentifyUtil.openCustomView(text)

        mainHandler.postDelayed(updateTask,2000)
    }


    /**
     * 发送TTS反馈到眼镜端（由眼镜播放语音）
     */
    private fun sendTtsFeedback(feedbackText: String) {
//        Log.d(TAG, "发送TTS反馈：$feedbackText")
        CxrApi.getInstance().notifyAiStart()
        CxrApi.getInstance().sendAsrContent(feedbackText)

//        val status = CxrApi.getInstance().sendTtsContent(feedbackText)
//        if (status != ValueUtil.CxrStatus.REQUEST_SUCCEED) {
////            Log.e(TAG, "TTS反馈发送失败，状态：$status")
//        } else {
//            // 通知眼镜TTS播放结束（可选，根据业务需求）
////            CxrApi.getInstance().notifyTtsAudioFinished()
//        }
    }

    private var mGroupDialog: BasePopupView? = null

    private fun showBiologyGroupDialog() {
        if (mGroupDialog != null) {
            mGroupDialog?.show()
            return
        }
        if (groupList.size == 0) {
            var group1 = GroupsEntity(
                "鸟类",
                "birdv2",
                "https://19106065.zhimakaifa.com/userfiles/upload/animal/202209151650345325.png"
            );
            var group2 = GroupsEntity(
                "植物",
                "plant",
                "https://19106065.zhimakaifa.com/userfiles/upload/animal/202209151650441714.png"
            );
            var group3 = GroupsEntity(
                "兽类",
                "mammalia",
                "https://19106065.zhimakaifa.com/userfiles/upload/animal/202211172055013607.png"
            );
            var group4 = GroupsEntity(
                "蝴蝶",
                "butterfly_v1",
                "https://19106065.zhimakaifa.com/userfiles/upload/animal/202209151651379558.png"
            );
            var group5 = GroupsEntity(
                "两栖",
                "amphibia",
                "https://19106065.zhimakaifa.com/userfiles/upload/animal/202209151651462729.png"
            );
            var group6 = GroupsEntity(
                "爬行",
                "reptilia",
                "https://19106065.zhimakaifa.com/userfiles/upload/animal/202209151651573706.png"
            );
            var group7 = GroupsEntity(
                "昆虫",
                "insectfamily_v3",
                "https://19106065.zhimakaifa.com/userfiles/upload/animal/202210260024396216.png"
            );
            groupList.add(group1)
            groupList.add(group2)
            groupList.add(group3)
            groupList.add(group4)
            groupList.add(group5)
            groupList.add(group6)
            groupList.add(group7)
        }
        mGroupDialog = DialogUtils.getInstance(this).setCanDismiss(true)
            .setLayoutId(R.layout.dialog_biology_group_lay, object : DialogConvert {
                override fun convertView(
                    holder: ViewHolder, popupView: BasePopupView
                ) {
                    val rvList: RecyclerView = holder.getView(R.id.rv_biology_group)
                    val ivClose: ImageView = holder.getView(R.id.iv_close)

                    val gridLayoutManager = GridLayoutManager(this@IdentityActivity, 3)
                    rvList.setLayoutManager(gridLayoutManager)
                    val rvAdapter: RvManyLayoutAdapter<GroupsEntity> =
                        object : RvManyLayoutAdapter<GroupsEntity>() {
                            public override fun getViewResId(item: GroupsEntity): Int {
                                return R.layout.item_biology_group
                            }

                            public override fun convert(
                                holder: RvBaseHolder,
                                groupItem: GroupsEntity,
                                viewtype: Int,
                                position: Int
                            ) {
                                if (viewtype == R.layout.item_biology_group_space) {
                                    return
                                }
                                val ivGroupImg: RCImageView =
                                    holder.getView(R.id.iv_biology_group_img)
                                val tvGroupName: TextView =
                                    holder.getView(R.id.tv_biology_group_name)

                                val item: GroupsEntity = groupItem

                                GlideImageLoadUtils.loadImage(
                                    item.url, ivGroupImg
                                )

                                tvGroupName.setText(item.name)

                                holder.getRootView().setOnClickListener({ v ->
                                    popupView.dismiss()
                                    mBiologyGroup = groupItem
                                    tv_biology_select?.setText(mBiologyGroup?.name)
                                })
                            }
                        }
                    rvList.setAdapter(rvAdapter)

                    ivClose.setOnClickListener(View.OnClickListener { view: View? ->
                        popupView.dismiss()
//                        setSelectPicture(false)
                    })

                    rvAdapter.setDatas(groupList)
                }
            }).bulid().showCustomCenterDialog()
    }


    fun uploadIndentifyImg(imgPath: String) {
        val uploadMap = HashMap<String, String>()
//        val loginResult: UserInfo = UserManager.getInstance().getUserInfo()
        uploadMap.put("uid", Constant.userId)
        uploadMap.put("source", Constant.SOURCE)
        uploadMap.put(
            "vcode",
            MD5Utils.MD5(MD5Utils.MD5(Constant.userId) + MD5Utils.MD5(Constant.SOURCE) + Constant.userId)
        )

        uploadSingleImg(Constant.API_UPLOAD_INDENTIFY__IMG, imgPath, uploadMap)
    }

    /**
     * 上传单张图片
     * @param filePath 图片地址
     * @param paramMaps 额外参数
     */
    private fun uploadSingleImg(
        url: String, filePath: String, paramMaps: HashMap<String, String>
    ) {
        uploadImg(
            url,
            filePath,
            paramMaps,
            object : BaseObserver<UploadImgEntity>(this@IdentityActivity, true) {
                public override fun success(result: UploadImgEntity?) {
//                getView().uploadSucc(result)
                }

                public override fun fail(msg: String) {
                }

            })
    }

    /**
     * 上传单张图片
     * @param filePath 图片地址
     * @param paramMaps 额外参数
     * @param baseObserver·回调
     */
    private fun uploadImg(
        url: String,
        filePath: String,
        paramMaps: java.util.HashMap<String, String>,
        baseObserver: BaseObserver<UploadImgEntity>
    ) {
//        CompressUtils.compressFile(mContext, File(filePath), object : CompressListener() {
//            public override fun onSuccess(file: File?) {
//                HttpUtil.getInstance().uploadFileReq(url, file, paramMaps, baseObserver)
//            }
//
//            public override fun onFail() {
//                hintWaitingDialog()
//                showError("")
//            }
//        })
    }


    private fun uploadPoiImg(imgEntity: UploadImgEntity) {

        val reqMap = HashMap<String, Any?>()

        reqMap.put("groupsid", mBiologyGroup?.groupsId)
        reqMap.put("lat", "38")
        reqMap.put("lng", "120")
        reqMap.put("pic", imgEntity)

    }


}

